<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭"
  >
        <a-spin tip="Loading..." :spinning="false">
          <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px" v-if="visible">
            <a-col :md="12" :sm="24">
              <a-card :bordered="false">
                <a-form layout="inline" @keyup.enter.native="searchQuery">
                  <a-row :gutter="24">
                    <a-col :xl="10" :lg="9" :md="8" :sm="24">
                      <a-form-item label="活动编码">
                        <a-input placeholder="请输入编码模糊查询" v-model="queryParam.actCode"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :xl="10" :lg="9" :md="8" :sm="24">
                      <a-form-item label="活动名称">
                        <a-input placeholder="请输入名称模糊查询" v-model="queryParam.actName"></a-input>
                      </a-form-item>
                    </a-col>

                    <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                      <a-col :xl="4" :lg="6" :md="8" :sm="24">
                        <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                      </a-col>
                    </div>
                  </a-row>
                </a-form>
                <a-table
                  ref="table"
                  size="middle"
                  bordered
                  :scroll="{
          x:'max-content'
        }"
                  tableLayout="auto"
                  rowKey="actCode"
                  :columns="dataColumns.slice(0,-1)"
                  :dataSource="allData"
                  :pagination="ipagination"
                  :loading="loading"
                  :rowSelection="{selectedRowKeys: selectedRowKeys, onSelect: onSelect,onSelectAll:onSelectAll}"
                  @change="handleTableChange"
                >
                  <template slot="imgUrl" slot-scope="text, record, index">
                    <div class="anty-img-wrap">
                      <a-avatar shape="square" :src="record.imgUrl" icon="user"/>
                    </div>
                  </template>

                  <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>
                </a-table>

              </a-card>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-card :bordered="false">
                <a-table
                  ref="table"
                  size="middle"
                  bordered
                  :scroll="{
          x:'max-content'
        }"
                  tableLayout="auto"
                  rowKey="actCode"
                  :columns="dataColumns"
                  :dataSource="selectData"
                >

                  <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>

                  <template slot="action" slot-scope="text, record, index">
                    <a @click="handleDelete(record)">删除</a>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-spin>
  </j-modal>
</template>

<script>
  import {filterObj} from '@/utils/util'
  import {queryDepartTreeList, getUserList, queryUserByDepId} from '@/api/api'
  import {getAction, postAction} from "@/api/manage";
  import JInput from '@/components/cn-form/JInput.vue';
  import SelectPosition from '@/components/cn-components/select-position'
  import {PageListMixin} from '@/mixins/PageListMixin'

  export default {
    name: 'act-modal',
    components: {JInput,SelectPosition},
    props: ['modalWidth', 'multi', 'userIds'],
    data() {
      return {
        typeLoading:false,
        queryParam: {
          code: "",
          name: "",
        },
        allData:[],
        selectData:[],
        dataColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '活动编号',
            align:"center",
            dataIndex: 'actCode'
          },
          {
            title: '活动名',
            align:"center",
            dataIndex: 'actName'
          },
          {
            title: '申请人账号',
            align:"center",
            dataIndex: 'applyUserBy'
          },
          {
            title: '申请人姓名',
            align:"center",
            dataIndex: 'applyUserName'
          },
          {
            title: '申请时间',
            align:"center",
            dataIndex: 'applyTime'
          },
          {
            title: '活动类型',
            align:"center",
            dataIndex: 'actType'
          },
          {
            title: '活动开始时间',
            align:"center",
            dataIndex: 'actBeginDate'
          },
          {
            title: '活动结束时间',
            align:"center",
            dataIndex: 'actEndDate'
          },
          {
            title: '备注',
            align:"center",
            dataIndex: 'remarks'
          },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            width: 80,
            ellipsis: true,
            scopedSlots: {customRender: 'action'},
          },
        ],
        scrollTrigger: {},
        selectedRowKeys: [],
        title: '活动选择',
        selectedKeys: [],
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        expandedKeys: [],
        reqCode: '',
        activeKey: '1',
        url: {
          list:  window._CONFIG['domianTpmURL']+ "/audit/tpmAuditAct/findSelectOptionalPageList",
          selected:  window._CONFIG['domianTpmURL'] + '/audit/tpmAuditAct/findSelectPageList'
        },
        record:null
      }
    },
    mixins: [PageListMixin],
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio';
      }
    },
    watch: {
      visible(v) {
        if (v) {
          this.$nextTick(()=>{
            this.loadData()
          })
        }
      },

      reqCode() {
        this.getSelectdData()
      }
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize();
    },
    methods: {


      /**
       * 获取已选中数据
       */
      getSelectdData() {
        postAction(this.url.selected, {tempUuid: this.reqCode}).then(res => {
          const {result} = res
          this.record = result
          if (result && result && result.length) {
            const actselect = result
            this.selectedKeys = actselect.map(type => type.actCode)
            this.selectedRowKeys = actselect.map(row => row.actCode);
            this.selectionRows = actselect
          }
        })
      },

      /**
       * 删除已选中活动
       * @param record
       */
      handleDelete(record) {
        this.selectData.remove(record)
        this.selectionRows.remove(record)
        this.selectedRowKeys.remove(record['actCode'])
      },
      /**
       * 覆盖mixin的loadData方法
       * @param arg
       * @returns {Promise<void>}
       */
      async loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        this.loading = true
        let params = this.getQueryParams()//查询条件
        await postAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.allData = res.result.records
            this.ipagination.total = res.result.total
          }
        }).finally(() => {
          this.loading = false
        })
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      },
      showModal(tempUuid) {
        this.visible = true;
        this.reqCode = tempUuid
      },
      /**
       * 获取查询参数
       * @returns {*}
       */
      getQueryParams() {
        let param = Object.assign({}, this.queryParam);
        param.current = this.ipagination.current;
        param.size = this.ipagination.pageSize;
        return filterObj(param);
      },
      searchReset(num) {
        let that = this;
        if (num !== 0) {
          that.loadData(1);
        }
        that.selectedRowKeys = [];
        that.selectionRows = [];
        that.selectedKeys = [];
        that.selectData = []
      },
      close() {
        this.searchReset(0);
        this.visible = false;
      },
      handleSubmit() {
        let that = this;
        that.$emit('ok', that.selectData);
        that.searchReset(0)
        that.close();
      },
      /**
       * 手动全选/取消全选活动
       * @param selected
       * @param selectedRows
       * @param changeRows
       */
      onSelectAll(selected, selectedRows, changeRows) {
        this.selectedRowKeys = selectedRows.map(row => row.actCode);
        this.selectionRows = selectedRows
        if (selected) {
          //todo 选中
          changeRows.map(row => {
            this.selectData.push(row)
          })
        } else {
          //todo 取消选中
          changeRows.map(row => {
            this.selectData.remove(row)
          })
        }
      },

      /**
       * 手动勾选/取消活动
       * @param record
       * @param selected
       * @param selectedRows
       * @param nativeEvent
       */
      onSelect(record, selected, selectedRows, nativeEvent) {
        this.selectedRowKeys = selectedRows.map(row => row.actCode);
        this.selectionRows = selectedRows
        if (selected) {
          //todo 选中
          this.selectData.push(record)
        } else {
          //todo 取消选中
          this.selectData.remove(record)
        }


      },
      onSearch() {
        this.loadData(1);
      },
      modalFormOk() {
        this.loadData();
      },

    }
  }
</script>

<style scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>
